package controller

import (
	"gin_server/internal/request"
	"gin_server/internal/service"
	"gin_server/pkg/response"

	"github.com/gin-gonic/gin"
)

type EmailController struct {
	service        service.EmailService
	captchaService service.CaptchaService
}

func NewEmailController(s service.EmailService, cs service.CaptchaService) *EmailController {
	return &EmailController{service: s, captchaService: cs}
}

// SendVerificationCode 发送邮箱验证码
// @Summary 发送邮箱验证码
// @Description 向指定邮箱发送验证码，用于登录或注册验证
// @Tags 邮箱
// @Accept json
// @Produce json
// @Param entity query request.SendVerificationCodeRequest true "邮箱信息"
// @Success 200 {object} response.Response{data=nil}
// @Router /email/code [get]
func (c *EmailController) SendVerificationCode(ctx *gin.Context) {
	var req request.SendVerificationCodeRequest
	if err := ctx.ShouldBindQuery(&req); err != nil {
		response.BadRequest(ctx, err.Error())
		return
	}

	// 验证验证码
	valid, err := c.captchaService.VerifyCaptcha(req.CaptchaID, req.CaptchaValue)
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	if valid {
		// 调用服务层发送验证码
		err := c.service.SendVerificationCode(req.Email)
		if err != nil {
			response.Error(ctx, "验证码发送失败")
			return
		}
	} else {
		response.Error(ctx, "验证码错误")
		return
	}
	response.SuccessWithMessage(ctx, "验证码已发送，请注意查收", nil)
}
